package com.ck.framework.web.service;

import com.ck.common.entity.SysUser;
import com.ck.common.enums.UserStatus;
import com.ck.common.exception.BusinessException;
import com.ck.common.utils.MessageUtils;
import com.ck.common.utils.txt.StringUtils;
import com.ck.common.vo.LoginUserVo;
import com.ck.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author ck
 * @date 2023/3/23 9:55
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService userService;

    @Autowired
    SysPasswordService passwordService;

    @Autowired
    SysPermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        SysUser user = userService.selectUserByUserName(username);
        //如果查询不到数据就通过抛出异常来给出提示
        if (StringUtils.isNull(user)){
            log.info("登录用户：{} 不存在.", username);
            throw new BusinessException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new BusinessException(MessageUtils.message("user.password.delete"));
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new BusinessException(MessageUtils.message("user.blocked"));
        }

        //校验密码
        passwordService.validate(user);

        return createLoginUser(user);
    }

    private UserDetails createLoginUser(SysUser user) {
        //去数据库查询 该登录用户 的权限
        Set<String> hashSet =permissionService.getMenuPermission(user);
        //封装成UserDetails对象返回
        return new LoginUserVo(user.getUserId(),user.getDeptId(), user,hashSet);
    }


}
